package net.caidingke.shepherd.config;

import net.caidingke.shepherd.profile.CurrentUserHandlerMethodArgumentResolver;
import net.caidingke.shepherd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * @author bowen.
 */
@Configuration
public class CustomWebMvcConfigurerAdapter implements WebMvcConfigurer {

    private static final String CONTENT_TYPE = "content-type";

    private final UserService userService;

    @Autowired
    public CustomWebMvcConfigurerAdapter(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new CurrentUserHandlerMethodArgumentResolver(userService));
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
        configurer.defaultContentTypeStrategy(
                webRequest -> {
                    if (webRequest.getHeader(CONTENT_TYPE) != null) {
                        switch (webRequest.getHeader(CONTENT_TYPE)) {
                            case MediaType.APPLICATION_JSON_VALUE:
                                return Collections.singletonList(MediaType.APPLICATION_JSON);
                            case MediaType.APPLICATION_XML_VALUE:
                                return Collections.singletonList(MediaType.APPLICATION_XML);
                            default:
                                return Collections.singletonList(MediaType.APPLICATION_JSON);
                        }
                    } else {
                        return Collections.singletonList(MediaType.APPLICATION_JSON);
                    }
                });
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry
                .addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 解决跨域 不限制任何请求
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE");
    }

}
